//
//  DeviceSelectViewController.m
//  BluetoothBalloonHangingBasket
//
//  Created by FENGYL on 2016/12/9.
//  Copyright © 2016年 FENGYL. All rights reserved.
//

#import "DeviceSelectViewController.h"
#import "BluetoothControlViewController.h"
#import <BabyBluetooth.h>
#import <MBProgressHUD.h>

static NSString * cellIdentifier = @"cell";

@interface DeviceSelectViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *bluetoothListTableView;

@property (strong ,nonatomic) BabyBluetooth * baby;
@property (strong , nonatomic) NSMutableArray * bluetoothArray;
@property (strong , nonatomic) MBProgressHUD * connectingHud;
@property (weak, nonatomic) IBOutlet UIButton *refreshButton;

@end

@implementation DeviceSelectViewController

-(NSMutableArray *)bluetoothArray{
    
    if (!_bluetoothArray) {
        _bluetoothArray = [NSMutableArray array];
    }
    return _bluetoothArray;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.bluetoothListTableView.delegate = self;
    self.bluetoothListTableView.dataSource = self;
    
    //处理多余线
    self.bluetoothListTableView.tableFooterView = [[UIView alloc]init];
    
    
    [self setViewShadow:self.refreshButton];
    
    //蓝牙
    self.baby = [BabyBluetooth shareBabyBluetooth];
    
    [self babyDelegate];
    
    self.baby.scanForPeripherals().begin();
    
    [self pleaseOpenBluetooth];
    
    [self bluetoothConnectSuccessOrFail];
    
    [self addObserver:self forKeyPath:@"bluetoothArray" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
    
}

-(void)viewDidDisappear:(BOOL)animated{
    
    [self.baby cancelScan];
    
}

#pragma mark 阴影效果
-(void)setViewShadow:(UIView *)sender{
    
    sender.layer.shadowColor = [UIColor blackColor].CGColor;
    
    sender.layer.shadowOffset = CGSizeMake(2, 2);
    
    sender.layer.shadowOpacity = 0.4;
    
    sender.layer.shadowRadius = 4;
    
}

#pragma mark 连接成功与否
-(void)bluetoothConnectSuccessOrFail{
    
    __block DeviceSelectViewController * safeSelf = self;
    
    [self.baby setBlockOnConnected:^(CBCentralManager *central, CBPeripheral *peripheral) {
        
        [safeSelf.connectingHud hideAnimated:YES];
        
        UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        BluetoothControlViewController * bluetoothControlViewController = [storyboard instantiateViewControllerWithIdentifier:@"BluetoothControlViewController"];
        
        [safeSelf.navigationController presentViewController:bluetoothControlViewController animated:YES completion:nil];
        
        NSLog(@"success");
        
    }];
    
   [self.baby setBlockOnFailToConnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
       
       [safeSelf.connectingHud.label setText:@"Fail to connect."];
       
       [safeSelf.connectingHud hideAnimated:YES afterDelay:0.5];
       
   }];
    
}

#pragma mark 提示打开蓝牙
-(void)pleaseOpenBluetooth{

    if (self.baby.centralManager.state != CBManagerStatePoweredOn) {
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Please open bluetooth." message:@"Open bluetooth" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction * cancelAlertAction = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:cancelAlertAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    
    
    
    
}

#pragma mark 设置蓝牙
-(void)babyDelegate{
    
    __block DeviceSelectViewController * safeSelf = self;
    
    //设置扫描到设备的委托
    [self.baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        
        if (![safeSelf.bluetoothArray containsObject:peripheral]) {
            
            [[safeSelf mutableArrayValueForKey:@"bluetoothArray" ]  addObject:peripheral];
            
        }
        NSLog(@"搜索到了设备:%@",peripheral.name);
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 设置tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.bluetoothArray.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CBPeripheral * peripheral = self.bluetoothArray[indexPath.row];
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        
    }
    
    if (peripheral.name == NULL) {
        
        [cell.textLabel setText:@"NULL"];
        
    }else{
        
        [cell.textLabel setText:peripheral.name];
        
    }
    
    [cell.detailTextLabel setText:peripheral.identifier.UUIDString];
    
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self.baby cancelAllPeripheralsConnection];
    
    [self bluetoothConnectSuccessOrFail];
    
    CBPeripheral * peripheral = self.bluetoothArray[indexPath.row];
    
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    
    [self.baby setBabyOptionsWithScanForPeripheralsWithOptions:scanForPeripheralsWithOptions connectPeripheralWithOptions:nil scanForPeripheralsWithServices:nil discoverWithServices:nil discoverWithCharacteristics:@[[CBUUID UUIDWithString:@"0000ffe1-0000-1000-8000-00805f9b34fb"]]];
    
    self.baby.having(peripheral).connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
    
    self.connectingHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.connectingHud.label setText:@"Connecting..."];
    // 再设置模式
    self.connectingHud.mode = MBProgressHUDModeIndeterminate;
    
    // 隐藏时候从父控件中移除
    self.connectingHud.removeFromSuperViewOnHide = YES;
    
    
    
}

#pragma mark 监听事件
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"bluetoothArray"]) {
        
        [self.bluetoothListTableView reloadData];
        
    }
    
}

#pragma mark 刷新列表
- (IBAction)refreshBluetoothList:(id)sender {
    
    [self pleaseOpenBluetooth];
    
    [self.bluetoothArray removeAllObjects];
    
    [self.baby cancelScan];
    
    self.baby.scanForPeripherals().begin();
    
}

-(void)dealloc{
    
    [self removeObserver:self forKeyPath:@"bluetoothArray"];

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
